﻿using MediatR;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using RedDragon.Common.Domain.AuthorizeRBAC;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.RBAC.API.Application.Common.Client;
using RedDragon.RBAC.ErrorCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.WorkCenter
{
    public class ImportClientHandler : IRequestHandler<ImportClientCommand, Result>
    {
        /// <summary>
        /// 工作表仓储
        /// </summary>
        public readonly IBaseRepository<Clients> clientsRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ImportClientHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="clientsRepository"></param>
        /// <param name="logger"></param>
        public ImportClientHandler(IBaseRepository<Clients> clientsRepository, ILogger<ImportClientHandler> logger)
        {
            this.clientsRepository = clientsRepository;
            this.logger = logger;
        }

        public async Task<Result> Handle(ImportClientCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            // 获取文件扩展名 判断上传文件类型是否正确
            var ext = Path.GetExtension(request.file.FileName);
            if (ext == ".xls" || ext == ".xlsx")
            {

            }
            else
            {
                result.Msg = "您上传的文件类型不正确";
                return result;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                request.file.CopyTo(ms);
                ms.Position = 0;

                //根据文件扩展名创建对应的工作簿对象(HSSFWorkbook用于.xls，XSSFWorkbook用于.xlsx)
                //获取工作簿
                IWorkbook wb = null;
                if (ext == ".xls")//创建97-2003
                {
                    wb = new HSSFWorkbook(ms);
                }
                else//创建2007及以上版本
                {
                    wb = new XSSFWorkbook(ms);
                }

                //获取sheet 获取工作簿中的第一个工作表
                ISheet sheet = wb.GetSheetAt(0);

                int totalRows = sheet.LastRowNum;//总行数
                int totalCells = sheet.GetRow(0).LastCellNum;//总列数

                //创建一个用于存储解析后的数据列表
                var workCentersList = new List<Clients>();

                //循环总行数 开头必须是1 不然从表头开始
                //遍历工作表的每一行（从第二行开始，因为第一行通常是表头）
                for (int i = 1; i <= totalRows; i++)
                {
                    //获取当前行
                    IRow row = sheet.GetRow(i);

                    //这个类必须写到循环里边 不然你批量添加只能添加一行
                    var dto = new Clients();// 在循环内创建新的对象实例

                    //下标从0开始 导入时 外键需进行判断 客户不知道你是外键 只会输入文字 需要在后台判断
                    var workCenterCode = row.GetCell(0).ToString();

                    dto.ClientsNo = row.GetCell(0).ToString();
                    dto.ClientsName = row.GetCell(1).ToString();
                    dto.ClientsType = row.GetCell(2).ToString();
                    dto.ClientsAdds = row.GetCell(3).ToString();
                    dto.ClientsTell = row.GetCell(4).ToString();
                    dto.ClientsCity = row.GetCell(5).ToString();
                    dto.ClientsSmar = row.GetCell(6).ToString();


                    //添加到数据集合中
                    workCentersList.Add(dto);
                }
                //跳出循环后 使用AddRange进行批量添加
                var res = clientsRepository.AddRange(workCentersList);
                //判断
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "导入成功";
                }
                else
                {
                    result.Msg = "导入失败";
                }


            }
            return result;

        }






    }
}



